#!/usr/bin/env python
#encoding: utf-8
#功能：使用python代码发送和接收邮件

from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart 
from email.MIMEBase import MIMEBase
from email.utils import parseaddr, formataddr
import smtplib

# 可以由用户输入
#from_addr = raw_input('From: ')
#password = raw_input('Password: ')
#to_addr = raw_input('To: ')
#smtp_server = raw_input('SMTP server: ')
from_addr = 'xxxxxxxx@163.com'
password = 'xxxxxxxxxxx' 
to_addr = 'xxxxxxxxx@qq.com'
smtp_server = 'smtp.163.com'

# 格式化邮件地址
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr(( \
        Header(name, 'utf-8').encode(), \
        addr.encode('utf-8') if isinstance(addr, unicode) else addr))

def send_text_mail():
    
    msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')          # 邮件正文内容
    msg['From'] = _format_addr(u'Python爱好者 <%s>' % from_addr)          # 发件人
    msg['To'] = _format_addr(u'管理员 <%s>' % to_addr)                    # 收件人
    msg['Subject'] = Header(u'来自SMTP的问候......', 'utf-8').encode()    # 邮件主题
    
    server = smtplib.SMTP(smtp_server, 25)
    server.set_debuglevel(0)    # 0:不输出信息    1:输出适当的交互信息
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())    # to_addr加[]是列表格式, 可以发送给多个收件人
    server.quit()

def send_html_mail():
    msg = MIMEText('<html><body><h1>Hello</h1>' + \
                   '<p>send by <a href="http://www.python.org">Python</a>...</p>' + \
                   '</body></html>', 'html', 'utf-8')
    msg['From'] = _format_addr(u'Python爱好者 <%s>' % from_addr)          # 发件人
    msg['To'] = _format_addr(u'管理员 <%s>' % to_addr)                    # 收件人
    msg['Subject'] = Header(u'来自SMTP的问候......', 'utf-8').encode()    # 邮件主题
    
    server = smtplib.SMTP(smtp_server, 25)
    server.set_debuglevel(0)    # 0:不输出信息    1:输出适当的交互信息
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())    # to_addr加[]是列表格式, 可以发送给多个收件人
    server.quit()

def send_attachment_mail():
    msg = MIMEMultipart()
    msg['From'] = _format_addr(u'Python爱好者 <%s>' % from_addr)
    msg['To'] = _format_addr(u'管理员 <%s>' % to_addr)
    msg['Subject'] = Header(u'来自SMTP的问候……', 'utf-8').encode()
    
    # 邮件正文是MIMEText:
    msg.attach(MIMEText('send with file...', 'plain', 'utf-8'))
    # 添加附件就是加上一个MIMEBase，从本地读取一个图片:
    with open('/root/test.png', 'rb') as f:
        # 设置附件的MIME和文件名，这里是png类型:
        mime = MIMEBase('image', 'png', filename='test.png')
        # 加上必要的头信息:
        mime.add_header('Content-Disposition', 'attachment', filename='test.png')
        mime.add_header('Content-ID', '<0>')
        mime.add_header('X-Attachment-Id', '0')
        # 把附件的内容读进来:
        mime.set_payload(f.read())
        # 用Base64编码:
        encoders.encode_base64(mime)
        # 添加到MIMEMultipart:
        msg.attach(mime)

    server = smtplib.SMTP(smtp_server, 25)
    server.set_debuglevel(0)    # 0:不输出信息    1:输出适当的交互信息
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())    # to_addr加[]是列表格式, 可以发送给多个收件人
    server.quit()

# 邮件正文中加入图片，图片是引用附件的格式，不能直接以外链的形式写入html.(容易被mail服务商过滤)
def send_photo_mail():
    msg = MIMEMultipart()
    msg['From'] = _format_addr(u'Python爱好者 <%s>' % from_addr)
    msg['To'] = _format_addr(u'管理员 <%s>' % to_addr)
    msg['Subject'] = Header(u'来自SMTP的问候……', 'utf-8').encode()
    
    # 邮件正文是MIMEText:
    msg.attach(MIMEText('<html><body><h1>Hello</h1>' +
                        '<p><img src="cid:0"></p>' +    # 正文引用附件中图片，附件不会再显示
                        '<p><img src="cid:1"></p>' +
                        '</body></html>', 'html', 'utf-8'))
    # 添加附件就是加上一个MIMEBase，从本地读取一个图片:
    with open('/root/test.png', 'rb') as f:
        # 设置附件的MIME和文件名，这里是png类型:
        mime = MIMEBase('image', 'png', filename='test.png')
        # 加上必要的头信息:
        mime.add_header('Content-Disposition', 'attachment', filename='test.png')
        mime.add_header('Content-ID', '<0>')
        mime.add_header('X-Attachment-Id', '0')
        # 把附件的内容读进来:
        mime.set_payload(f.read())
        # 用Base64编码:
        encoders.encode_base64(mime)
        # 添加到MIMEMultipart:
        msg.attach(mime)

    with open('/root/test1.png', 'rb') as f:
        # 设置附件的MIME和文件名，这里是png类型:
        mime = MIMEBase('image', 'png', filename='test1.png')
        # 加上必要的头信息:
        mime.add_header('Content-Disposition', 'attachment', filename='test1.png')
        mime.add_header('Content-ID', '<1>')
        mime.add_header('X-Attachment-Id', '1')
        # 把附件的内容读进来:
        mime.set_payload(f.read())
        # 用Base64编码:
        encoders.encode_base64(mime)
        # 添加到MIMEMultipart:
        msg.attach(mime)

    server = smtplib.SMTP(smtp_server, 25)
    server.set_debuglevel(0)    # 0:不输出信息    1:输出适当的交互信息
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())    # to_addr加[]是列表格式, 可以发送给多个收件人
    server.quit()

# 如果不支持html的设备可以降级使用plain纯文本邮件
def send_text_html_mail():
    msg = MIMEMultipart('alternative')
    msg['From'] = _format_addr(u'Python爱好者 <%s>' % from_addr)
    msg['To'] = _format_addr(u'管理员 <%s>' % to_addr)
    msg['Subject'] = Header(u'来自SMTP的问候……', 'utf-8').encode()
    
    # 邮件正文是MIMEText:
    msg.attach(MIMEText('hello', 'plain', 'utf-8'))
    msg.attach(MIMEText('<html><body><h1>Hello</h1></body></html>', 'html', 'utf-8'))

    server = smtplib.SMTP(smtp_server, 25)
    server.set_debuglevel(0)    # 0:不输出信息    1:输出适当的交互信息
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())    # to_addr加[]是列表格式, 可以发送给多个收件人
    server.quit()

# gmail由于网络问题，很可能发送不过去
def send_tls_mail():
    smtp_server = 'smtp.gmail.com'    # 设置google的smtp
    smtp_port = 587                   # 设置端口号
    
    msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')
    msg['From'] = _format_addr(u'Python爱好者 <%s>' % from_addr)
    msg['To'] = _format_addr(u'管理员 <%s>' % to_addr)
    msg['Subject'] = Header(u'来自SMTP的问候……', 'utf-8').encode()
    
    server = smtplib.SMTP(smtp_server, smtp_port) 
    server.starttls()
    server.set_debuglevel(0)
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()

if __name__ == '__main__':
    #send_text_mail()
    #send_html_mail()
    #send_attachment_mail()
    #send_photo_mail()
    send_text_html_mail()
    
